﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TomMaton.Umbraco.AmazonS3
{
    public partial class AmazonS3 : System.Web.UI.UserControl
    {

        private string myAWSAccessKeyId = amazonS3Functionality.getKey("AccessKeyId", amazonS3Functionality.pluginConfigPath).ToString();
        private string mySecretAccesKeyId = amazonS3Functionality.getKey("SecretAccesKeyId", amazonS3Functionality.pluginConfigPath).ToString();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //jQueryFunctionality();
                generateBucketList();

            }
        }

        protected void cmdCreateBucket_Click(object sender, EventArgs e)
        {
            com.amazonaws.s3.doc.AmazonS3 myS3 = new com.amazonaws.s3.doc.AmazonS3();
            DateTime myTime = DateTime.Now;
            try
            {
                com.amazonaws.s3.doc.CreateBucketResult myCreateResult = myS3.CreateBucket(txtBucketName.Text.Replace(" ", ""),
                    null,
                    myAWSAccessKeyId,
                    S3Helper.GetTimeStamp(myTime),
                    true,
                    S3Helper.GetSignature(mySecretAccesKeyId, "CreateBucket", myTime));

                messageDisplay.Text = "Bucket successfully created";

                generateBucketList();

            }
            catch (Exception ex)
            {
                messageDisplay.Text = String.Format("CreateBucket Error: {0}", ex.Message);
            }
        }

        //This is of no use at the moment and will be added in a later version
        //protected void cmdDeleteBucket_Click(object sender, EventArgs e)
        //{
        //    com.amazonaws.s3.doc.AmazonS3 myS3 = new com.amazonaws.s3.doc.AmazonS3();
        //    DateTime myTime = DateTime.Now;

        //    try
        //    {
        //        for (int i = 0; i < S3Buckets.Items.Count; i++)
        //        {
        //            string checkedBox = ((CheckBox)S3Buckets.Items[i].FindControl("deleteBucket")).Checked.ToString();
        //            if (checkedBox == "True")
        //            {
        //                com.amazonaws.s3.doc.Status myDeleteResult = myS3.DeleteBucket(((HiddenField)S3Buckets.Items[i].FindControl("bucketName")).Value.ToString(),
        //                    myAWSAccessKeyId,
        //                    S3Helper.GetTimeStamp(myTime),
        //                    true,
        //                    S3Helper.GetSignature(mySecretAccesKeyId, "DeleteBucket", myTime),
        //                    null);                        
        //            }

        //            messageDisplay.Text = "Bucket sucessfully deleted";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        messageDisplay.Text = String.Format("S3 Bucket deletion error: {0}", ex.Message);
        //    }
        //}

        protected void cmdSubmitUpload_Click(object sender, EventArgs e)
        {
            if (fileUpload.HasFile)
            {
                messageDisplay.Text = String.Format("Server recieved {0}", fileUpload.FileName);

                com.amazonaws.s3.doc.AmazonS3 myS3 = new com.amazonaws.s3.doc.AmazonS3();
                DateTime myTime = DateTime.Now;

                //Create new signature for this operation
                string mySignature = S3Helper.GetSignature(mySecretAccesKeyId, "PutObjectInline", myTime);

                //Create a new access grant for anonymous users
                com.amazonaws.s3.doc.Grant myGrant = new com.amazonaws.s3.doc.Grant();
                com.amazonaws.s3.doc.Grant[] myGrants = new com.amazonaws.s3.doc.Grant[1];

                // Setup Access control, allow read access to all
                com.amazonaws.s3.doc.Group myGroup = new com.amazonaws.s3.doc.Group();
                myGroup.URI = "http://acs.amazonaws.com/groups/global/AllUsers";
                myGrant.Grantee = myGroup;
                myGrant.Permission = com.amazonaws.s3.doc.Permission.READ;
                myGrants[0] = myGrant;

                //Setup some metadata to indecate the content type
                com.amazonaws.s3.doc.MetadataEntry myContentType = new com.amazonaws.s3.doc.MetadataEntry();
                myContentType.Name = "ContentType";
                myContentType.Value = fileUpload.PostedFile.ContentType;

                com.amazonaws.s3.doc.MetadataEntry[] myMetaData = new com.amazonaws.s3.doc.MetadataEntry[1];
                myMetaData[0] = myContentType;

                string uploadedFileName = fileUpload.FileName.ToString();

                //Upload the file
                com.amazonaws.s3.doc.PutObjectResult myResult = myS3.PutObjectInline(
                    ddBucketList.SelectedValue.ToString(),
                    uploadedFileName,
                    myMetaData,
                    fileUpload.FileBytes,
                    fileUpload.FileBytes.Length,
                    myGrants,
                    com.amazonaws.s3.doc.StorageClass.STANDARD,
                    true,
                    myAWSAccessKeyId,
                    S3Helper.GetTimeStamp(myTime),
                    true,
                    mySignature,
                    null);

                if (myResult != null)
                    messageDisplay.Text = String.Format("File has been uploaded successfully");

                generateBucketList();
            }
        }

        protected string showContents(string bucketName)
        {
            com.amazonaws.s3.doc.AmazonS3 myS3 = new com.amazonaws.s3.doc.AmazonS3();
            DateTime myTime = DateTime.Now;
            string mySignature = S3Helper.GetSignature(mySecretAccesKeyId, "ListBucket", myTime);
            string bucketContentList = string.Empty;

            com.amazonaws.s3.doc.ListBucketResult myResults = myS3.ListBucket(bucketName.ToString(),
                "",
                "",
                0,
                false,
                "|",
                myAWSAccessKeyId,
                S3Helper.GetTimeStamp(myTime),
                true,
                mySignature,
                null);

            //Iterate through bucket contents
            if (myResults.Contents != null)
            {
                //Literal bucketContentContainer = new Literal();
                bucketContentList = "<ul>";

                foreach (com.amazonaws.s3.doc.ListEntry myBucketItem in myResults.Contents)
                {
                    bucketContentList += String.Format("<li><a href=\"{0}\">{1}</a></li>", String.Format("https://s3.amazonaws.com/{0}/{1}", bucketName, myBucketItem.Key), myBucketItem.Key);
                }
                bucketContentList += "</ul>";

                //bucketContentContainer.Text = bucketContentList;

                //base.Controls.Add(bucketContentContainer);
            }
            return bucketContentList;

        }

        protected void generateBucketList()
        {
            com.amazonaws.s3.doc.AmazonS3 myS3 = new com.amazonaws.s3.doc.AmazonS3();
            DateTime myTime = DateTime.Now;
            try
            {
                //List All buckets under this user
                com.amazonaws.s3.doc.ListAllMyBucketsResult myBuckets = myS3.ListAllMyBuckets(myAWSAccessKeyId,
                    S3Helper.GetTimeStamp(myTime),
                    true,
                    S3Helper.GetSignature(mySecretAccesKeyId, "ListAllMyBuckets", myTime));

                if (myBuckets.Buckets.Length > 0)
                {
                    ddBucketList.DataSource = myBuckets.Buckets;
                    ddBucketList.DataTextField = "Name";
                    ddBucketList.DataValueField = "Name";
                    ddBucketList.DataBind();
                }
                else
                {
                    foldersRequired.Visible = true;
                }


                string listedBuckets = "";


                foreach (com.amazonaws.s3.doc.ListAllMyBucketsEntry bucketEntry in myBuckets.Buckets)
                {
                    listedBuckets += String.Format("<div style=\"border:1px solid #cecece;margin-bottom:10px;\"><div class=\"menubar\"><a onlick=\"showItems();\" class=\"bucketName\" style=\"display:block;padding:5px 0 5px 10px;\">Folder name: {0}</a></div>", bucketEntry.Name.ToString());
                    listedBuckets += showContents(bucketEntry.Name.ToString());
                    listedBuckets += "</div>";
                }
                litS3Buckets.Text = listedBuckets;
            }
            catch (Exception error1)
            {
                Response.Write(error1);
            }
        }
    }
}